<?php

namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Helpers\Helper;
use App\Model\IpBlacklist;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;
use App\Model\User;
use App\Model\UserDevice;
use Phper666\JWTAuth\JWT;
use Hyperf\Di\Annotation\Inject;

class AuthBaseService extends BaseService
{
    /**
     * @Inject
     * @var JWT
     */
    protected $jwt;

    /**
     * 获取登录Token
     */
    protected function autoLogin($user = null)
    {
        $userData = [
            'uid' => $user->id,
            'account' => $user->user_name,
        ];
        $token = $this->jwt->getToken($userData);
        return $token;
    }

    /**
     * 注册检测
     */
    protected function checkRegister()
    {
        $clientIp = Helper::getClientIp();
        $deviceId = $this->request->input('cid', '');
        $phone = $this->request->input('phone', '');
        $phone = $this->request->input('phone', '');
        //白名单手机
        if ($this->checkWhitePhone($phone)) return ['errcode' => 0];
        $appId = $this->request->input('appid', 1);
        $blackPhonePrefix = ['170', '171', '162', '165', '167', '17821'];
        if (
            in_array(substr($phone, 0, 3), $blackPhonePrefix)
            || in_array(substr($phone, 0, 5), $blackPhonePrefix)
        ) {
            log_info(__METHOD__ . "==LmtPhone:{$phone}");
            return ['errcode' => ErrorCode::PHONE_LMT, 'errmsg' => "该手机号暂不允许注册～"];
        }
        //IP注册限制
        if (IpBlacklist::checkIpBlack($clientIp)) {
            return ['errcode' => ErrorCode::IP_LMT, 'errmsg' => "暂时不允许注册平台～"];
        }
        //设备注册次数
        $lmt = check_dev_env() ? 1000 : env('REG_DEVICE_LMT_NUM', 20);
        $regNum = User::checkDeviceNum($deviceId, $appId);
        //获取设备号白名单
        $device_id_unlimited = config('busi.device_id_unlimited') ? config('busi.device_id_unlimited') : [];
        if ($regNum >= $lmt && !in_array($deviceId,$device_id_unlimited)) {
            log_info(__METHOD__ . "==LmtDevice:{$deviceId}==RegNum:{$regNum}");
            return ['errcode' => ErrorCode::DEVICE_LMT, 'errmsg' => "注册次数超限；ErrCode:" . ErrorCode::DEVICE_LMT];
        }

        //IP注册次数
        $lmt = check_dev_env() ? 1000 : env('REG_IP_LMT_NUM', 20);
        $regNum = User::checkClientIpNum($clientIp, $appId);
        $ipUnlimited = config('busi.ip_unlimited') ? config('busi.ip_unlimited') : [];
        if ($regNum >= $lmt && !in_array($clientIp,$ipUnlimited)) {
            log_info(__METHOD__ . "==LmtIp:{$clientIp}==RegNum:{$regNum}");
            return ['errcode' => ErrorCode::IP_LMT, 'errmsg' => "注册次数超限；ErrCode:" . ErrorCode::IP_LMT];
        }
        return ['errcode' => 0];
    }

    /**
     * 注册用户
     */
    protected function doRegister($phone = '')
    {
        $allInputs = $this->request->all();
        log_info('注册用户'.json_decode($allInputs).'aaaa'.$allInputs['phone']);
        log_info(__CLASS__ . "注册数据打印日志".json_encode($allInputs));
        Db::beginTransaction();
        try {
            //注册用户表
            $user = User::createAccount([
                'phone' => $allInputs['phone'] ?? $phone,
                'version' => $allInputs['version'],
                'device_id' => $allInputs['cid'],
                'device' => $allInputs['device'],
                'client_ip' => Helper::getClientIp(),
                'platform' => $allInputs['platform'],
                'android_market' => $allInputs['android_market'] ?? '',
                'channel' => $allInputs['channel'],
                'app_id' => $allInputs['appid'],
                'oaid' => !empty($allInputs['oaid']) ? $allInputs['oaid'] : '',
                'oaid_md5' => !empty($allInputs['oaid']) ? md5($allInputs['oaid']) : '',
                'imei' => $allInputs['imei'] ?? ''
            ]);

            if (!$user) {
                Db::rollBack();
            }
            Db::commit();

            //注册回调处理
            $this->registerCallback();
            return $user;
        } catch (\Throwable $exception) {
            log_info(__METHOD__ . '==Error:' . $exception->getMessage());
            Db::rollBack();
        }
        return null;
    }

    /**
     * 手机登录（注册）
     */
    function authPhoneLogin($phone = '')
    {
        //查找用户是否存在
        $user = User::checkPhone($phone);

        //账号被冻结
        if ($user && $user->status == User::STATUS_FREEZE) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '该用户涉嫌违规已被冻结账号！');
        }

        if (!$user) {
            //注册检测
            $check = $this->checkRegister();
            if ($check['errcode'] > 0) return $this->setError($check['errcode'], $check['errmsg']);

            //执行注册
            $user = $this->doRegister($phone);
        }

        //记录设备ID
        if ($deviceId = $this->request->input('cid', '')) {
            UserDevice::addRecord($user->id, $deviceId);
        }

        //自动登录
        $userInfo = $this->packBaseUserInfo($user);

        //是否设置资料
        $fixProfile = !isset($userInfo['nick_name']) || !$userInfo['nick_name'] ? 1 : 0;

        //是否有融云账号
        if (!$user->im_account || !$user->im_token || $user->id <= env('RONG_NEW_START_UID', 803)) {
            $imInfo = User::createRongIMAccount($user->id, $userInfo['nick_name'] ?? '', $userInfo['avatar'] ?? '');
        } else {
            $imInfo = ['im_account' => $user->im_account, 'im_token' => $user->im_token];
        }

        return [
            //登录token
            'token' => $this->autoLogin($user),
            //需要完善个人资料
            'fix_profile' => $fixProfile,
            //个人资料
            'user_info' => $userInfo,
            //融云账号
            'im_info' => $imInfo
        ];
    }

    /**
     * 注册回调
     */
    function registerCallback()
    {
        return;
    }
}
